<template>
	<view class="container">
		<view class="bg-image">
			<view class="bg_img">
				<image src="https://terraria-1300530744.cos.ap-guangzhou.myqcloud.com/addserver/cli.png"
					mode="aspectFit"></image>
			</view>
			<view class="title">连接到您的服务器</view>
		</view>

		<view class="bg_box">
			<view class="IPserver">
				<view class="server_ip serverinfo_l">
					<view class="server_name">服务器IP</view>
					<view class="server_input">
						<input 
							v-model="serverIP" 
							placeholder="127.0.0.1" 
							placeholder-style="color: #999;" 
							:disabled="!isEditable"
							:class="{ 'disabled-input': !isEditable }"
						/>
					</view>
				</view>
				<view class="server_ip serverinfo_r">
					<view class="server_name">服务器端口</view>
					<view class="server_input">
						<input 
							v-model="serverPort" 
							placeholder="7777" 
							placeholder-style="color: #999;" 
							:disabled="!isEditable"
							:class="{ 'disabled-input': !isEditable }"
						/>
					</view>
				</view>
			</view>

			<view class="REST_box">
				<view class="server_ip REST">
					<view class="server_name">REST端口</view>
					<view class="server_input">
						<input 
							v-model="serverREST" 
							placeholder="7878" 
							placeholder-style="color: #999;" 
							:disabled="!isEditable"
							:class="{ 'disabled-input': !isEditable }"
						/>
					</view>
				</view>
				<view class="server_ip REST">
					<view class="server_name">REST密钥(token)</view>
					<view class="server_input">
						<input 
							v-model="serverRESTKey" 
							placeholder="123456" 
							placeholder-style="color: #999;" 
							:disabled="!isEditable"
							:class="{ 'disabled-input': !isEditable }"
						/>
					</view>
				</view>
			</view>

			<!-- 检查按钮 -->
			<view 
				class="jiancha" 
				@click="checkConnection"
				:class="{ 'disabled-btn': !isEditable }"
				:disabled="!isEditable"
			>
				<image src="https://terraria-1300530744.cos.ap-guangzhou.myqcloud.com/addserver/jiazai.png"
					mode="aspectFit"></image>
				<view style="margin-left: 6rpx;">检查连接</view>
			</view>
		</view>

		<!-- 服务器信息填写区域 -->
		<view class="server_Info" v-if="isflag">
			<!-- 服务器头像上传 -->
			<view class="info-section">
				<view class="info-label">服务器头像</view>
				<view class="avatar-upload">
					<!-- 已选择的头像预览 -->
					<view v-if="localFiles.avatarPath" class="avatar-preview">
						<image :src="localFiles.avatarPath" mode="aspectFill"></image>
						<view class="delete-btn" @click="deleteAvatar">
							<i class="fa fa-times"></i>
						</view>
					</view>

					<!-- 上传按钮 -->
					<view v-else class="upload-btn" @click="chooseAvatar">
						<i class="fa fa-plus"></i>
						<view class="upload-text">添加头像</view>
					</view>
					<view class="format-hint">支持jpg/png格式，建议尺寸200x200</view>
				</view>
			</view>

			<!-- 横条上传 -->
			<view class="info-section">
				<view class="info-label">服务器横条</view>
				<view class="banner-upload">
					<!-- 已选择的横条预览 -->
					<view v-if="localFiles.bannerPath" class="banner-preview-container">
						<view class="banner-preview">
							<image v-if="localFiles.bannerType === 'image'" :src="localFiles.bannerPath" mode="aspectFill"></image>
							<video v-else-if="localFiles.bannerType === 'video'" :src="localFiles.bannerPath" controls></video>
							<view v-else class="error-message">文件格式不支持</view>
						</view>
						<view class="delete-btn" @click="deleteBanner">
							<i class="fa fa-times"></i>
						</view>
					</view>

					<!-- 上传按钮 -->
					<view v-else class="upload-banner-btn" @click="showBannerOptions">
						<i class="fa fa-plus"></i>
						<view class="upload-text">添加横条</view>
					</view>
					<view class="format-hint">支持mp4/jpg/png格式，建议尺寸610x78</view>
				</view>
			</view>

			<!-- 服务器名称 -->
			<view class="info-section">
				<view class="info-label">服务器名称</view>
				<view class="text-input">
					<input v-model="formData.serverName" placeholder="请输入服务器名称" placeholder-style="color: #999;" />
				</view>
			</view>

			<!-- 服务器简介 -->
			<view class="info-section">
				<view class="info-label">服务器简介</view>
				<view class="textarea-input">
					<textarea v-model="formData.serverDescription" placeholder="请输入服务器简介"
						placeholder-style="color: #999; align-items: flex-start;" auto-height></textarea>
				</view>
			</view>

			<!-- 提交按钮 -->
			<view class="submit-btn" @click="submitForm" :class="{ 'disabled-btn': uploading }" :disabled="uploading">
				<view v-if="!uploading">提交服务器信息</view>
				<view v-if="uploading">提交中...</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { NEW_URL_DEV } from "@/common/config.js";
	// 假设从全局存储中获取用户openid
	// import { getStorageSync } from '@/common/storage.js';

	export default {
		data() {
			return {
				// 服务器连接信息
				serverIP: '',
				serverPort: '',
				serverREST: '',
				serverRESTKey: '',

				// 表单数据 - 与后端实体类对应
				formData: {
					uuid: '',
					openid: '',
					serverIp: '',
					serverPort: '',
					serverRest: '',
					serverRestKey: '',
					serverName: '',
					serverDescription: '',
					avatarUrl: '',
					bannerUrl: '',
					bannerType: ''
				},
				
				// 本地文件信息（不上传，仅用于预览）
				localFiles: {
					avatarPath: '',      // 头像本地临时路径
					bannerPath: '',      // 横条本地临时路径
					bannerType: ''       // 横条类型(image/video)
				},
				
				isflag: false,
				isEditable: true,
				// 上传中状态
				uploading: false
			}
		},
		onLoad() {
			// 获取当前用户openid（根据实际项目调整获取方式）
			// this.formData.openid = getStorageSync('openid') || '';
			this.formData.openid = '123456';
			// console.log('页面加载完成，获取到的openid:', this.formData.openid);
		},
		methods: {
			// 检查连接
			checkConnection() {
				console.log('开始检查连接，参数:', {
					serverIP: this.serverIP,
					serverPort: this.serverPort,
					serverREST: this.serverREST,
					serverRESTKey: this.serverRESTKey
				});
				
				if (!this.serverIP || !this.serverPort) {
					uni.showToast({
						title: '请填写服务器IP和端口',
						icon: 'none'
					});
					console.log('检查连接失败：服务器IP或端口未填写');
					return;
				}

				uni.showLoading({
					title: '正在检查连接...',
				});

				// 调用后端接口检查连接
				uni.request({
					url: NEW_URL_DEV + "/api/tshock/check-connectivity",
					method: "GET",
					data: {
						serverIp: this.serverIP,
						restPort: this.serverREST,
						token: this.serverRESTKey
					},
					success: (response) => {
						uni.hideLoading();
						console.log("连接验证结果:", response.data);
						
						if (response.data.success) {
							// 验证成功后初始化表单数据
							this.formData.serverIp = this.serverIP;
							this.formData.serverPort = this.serverPort;
							this.formData.serverRest = this.serverREST;
							this.formData.serverRestKey = this.serverRESTKey;
							
							uni.showToast({
								title: "连接成功: " + response.data.response,
								icon: "success"
							});
							this.isflag = true;
							this.isEditable = false;
							console.log('连接成功，表单数据初始化完成');
						} else {
							uni.showToast({
								title: "连接失败: " + response.data.error,
								icon: "none"
							});
							this.isflag = false;
							this.isEditable = true;
							console.log('连接失败: ' + (response.data.error || '未知错误'));
						}
					},
					fail: (err) => {
						uni.hideLoading();
						console.error("请求发送失败:", err);
						uni.showToast({
							title: "网络错误，请重试",
							icon: "none"
						});
						this.isEditable = true;
					}
				});
			},

			// 选择头像（仅本地预览）
			chooseAvatar() {
				console.log('开始选择头像');
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						console.log('头像选择成功，临时路径:', res.tempFilePaths[0]);
						this.localFiles.avatarPath = res.tempFilePaths[0];
						uni.showToast({
							title: '头像选择成功',
							icon: 'none'
						});
					},
					fail: (err) => {
						console.error('头像选择失败:', err);
						uni.showToast({
							title: '头像选择失败',
							icon: 'none'
						});
					}
				});
			},

			// 选择横条图片（仅本地预览）
			chooseBannerImage() {
				console.log('开始选择横条图片');
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: (imgRes) => {
						console.log('横条图片选择成功，临时路径:', imgRes.tempFilePaths[0]);
						this.localFiles.bannerPath = imgRes.tempFilePaths[0];
						this.localFiles.bannerType = 'image';
						uni.showToast({
							title: '图片选择成功',
							icon: 'none'
						});
					},
					fail: (err) => {
						console.error('横条图片选择失败:', err);
						uni.showToast({
							title: '图片选择失败',
							icon: 'none'
						});
					}
				});
			},

			// 选择横条视频（仅本地预览）
			chooseBannerVideo() {
				console.log('开始选择横条视频');
				uni.chooseVideo({
					sourceType: ['album', 'camera'],
					maxDuration: 60,
					camera: 'back',
					success: (videoRes) => {
						console.log('横条视频选择成功，临时路径:', videoRes.tempFilePath);
						this.localFiles.bannerPath = videoRes.tempFilePath;
						this.localFiles.bannerType = 'video';
						uni.showToast({
							title: '视频选择成功',
							icon: 'none'
						});
					},
					fail: (err) => {
						console.error('横条视频选择失败:', err);
						uni.showToast({
							title: '视频选择失败',
							icon: 'none'
						});
					}
				});
			},

			// 删除头像
			deleteAvatar() {
				console.log('删除头像');
				this.localFiles.avatarPath = '';
				uni.showToast({ title: '头像已删除', icon: 'none' });
			},

			// 显示横条选择选项
			showBannerOptions() {
				console.log('显示横条选择选项');
				uni.showActionSheet({
					itemList: ['上传图片', '上传视频'],
					success: (res) => {
						console.log('选择了横条类型，索引:', res.tapIndex);
						if (res.tapIndex === 0) {
							this.chooseBannerImage();
						} else {
							this.chooseBannerVideo();
						}
					},
					fail: (err) => {
						console.error('横条选择选项调用失败:', err);
					}
				});
			},

			// 删除横条
			deleteBanner() {
				console.log('删除横条');
				this.localFiles.bannerPath = '';
				this.localFiles.bannerType = '';
				uni.showToast({ title: '横条已删除', icon: 'none' });
			},

			// 上传单个文件到服务器
			uploadSingleFile(tempFilePath, type, fileType = '') {
				console.log(`开始上传${type}文件，路径:`, tempFilePath);
				return new Promise((resolve, reject) => {
					// 根据文件类型选择不同的接口路径
					let uploadUrl = '';
					if (type === 'avatar') {
						uploadUrl = NEW_URL_DEV + '/api/tshock/file/upload/avatar';
					} else if (type === 'banner') {
						uploadUrl = NEW_URL_DEV + '/api/tshock/file/upload/banner';
					}

					uni.uploadFile({
						url: uploadUrl,
						filePath: tempFilePath,
						name: 'file',
						// 横幅需要额外传递type参数（image/video）
						formData: type === 'banner' ? { 'type': fileType } : {},
						success: (uploadRes) => {
							console.log(`${type}文件上传响应:`, uploadRes);
							try {
								const data = JSON.parse(uploadRes.data);
								if (data.success) {
									console.log(`${type}文件上传成功，URL:`, data.url);
									resolve(data.url);
								} else {
									console.error(`${type}文件上传失败:`, data.message);
									reject(new Error(data.message || `${type}文件上传失败`));
								}
							} catch (e) {
								console.error(`${type}文件上传结果解析失败:`, e);
								reject(new Error('文件上传结果解析失败'));
							}
						},
						fail: (err) => {
							console.error(`${type}文件上传失败:`, err);
							reject(new Error('文件上传请求失败'));
						}
					});
				});
			},

			// 提交表单到后端
			async submitForm() {
				console.log('开始提交服务器信息');
				
				// 表单验证
				if (!this.formData.serverIp || !this.formData.serverPort) {
					console.log('提交失败：服务器IP或端口未填写');
					return uni.showToast({ title: '请填写服务器IP和端口', icon: 'none' });
				}
				
				if (!this.formData.serverName) {
					console.log('提交失败：服务器名称未填写');
					return uni.showToast({ title: '请填写服务器名称', icon: 'none' });
				}

				this.uploading = true;
				uni.showLoading({ title: '正在提交...' });

				try {
					// 1. 上传头像（如果有）
					if (this.localFiles.avatarPath) {
						console.log('开始上传头像');
						const avatarUrl = await this.uploadSingleFile(
							this.localFiles.avatarPath, 
							'avatar', 
							'image'
						);
						this.formData.avatarUrl = avatarUrl;
					}

					// 2. 上传横条（如果有）
					if (this.localFiles.bannerPath) {
						console.log('开始上传横条，类型:', this.localFiles.bannerType);
						const bannerUrl = await this.uploadSingleFile(
							this.localFiles.bannerPath, 
							'banner', 
							this.localFiles.bannerType
						);
						this.formData.bannerUrl = bannerUrl;
						this.formData.bannerType = this.localFiles.bannerType;
					}

					// 3. 提交服务器信息到后端（使用正确的接口路径）
					console.log('所有文件上传完成，开始提交服务器信息:', this.formData);
					
					uni.request({
						// 使用正确的接口路径，与后端TshockServerController匹配
						url: NEW_URL_DEV + '/api/tshock/server',
						method: 'POST',  // 与后端@PostMapping对应
						data: this.formData,
						// 后端有@Anonymous注解，无需认证头
						success: (res) => {
							this.uploading = false;
							uni.hideLoading();
							
							console.log('服务器信息提交响应:', res.data);
							if (res.data.success) {
								uni.showToast({
									title: '提交成功',
									icon: 'success'
								});
								// 提交成功后返回上一页
								setTimeout(() => {
									uni.navigateBack();
								}, 1500);
							} else {
								uni.showToast({
									title: res.data.message || '提交失败',
									icon: 'none'
								});
							}
						},
						fail: (err) => {
							this.uploading = false;
							uni.hideLoading();
							console.error('服务器信息提交失败:', err);
							uni.showToast({ title: '网络错误，请重试', icon: 'none' });
						}
					});

				} catch (error) {
					this.uploading = false;
					uni.hideLoading();
					console.error('提交过程出错:', error);
					uni.showToast({ 
						title: error.message || '提交失败，请重试', 
						icon: 'none' 
					});
				}
			}
		}
	}
</script>

<style lang="scss">
	/* 样式保持不变 */
	$primary-color: #3675c2;
	$primary-light: #e8f0fe;
	$secondary-color: #f59e0b;
	$border-color: #e5e7eb;
	$text-primary: #1f2937;
	$text-secondary: #6b7280;
	$text-placeholder: #9ca3af;
	$required-color: #ef4444;
	$delete-color: #e53e3e;
	$shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
	$shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
	$radius: 16rpx;

	.container {
		background-color: #f5f7fa;
		min-height: 100vh;
	}

	.disabled-input {
		background-color: #f3f4f6;
		color: #9ca3af;
		cursor: not-allowed;
		width: 100%;
		box-sizing: border-box;
	}

	.server_input input {
		width: 100%;
		height: 100%;
		padding-left: 20rpx;
		line-height: 61rpx;
		font-size: 26rpx;
		box-sizing: border-box;
	}

	.disabled-btn {
		background-color: #94a3b8;
		cursor: not-allowed;
		opacity: 0.8;
	}

	.upload-btn {
		width: 160rpx;
		height: 160rpx;
		border: 2px dashed $border-color;
		border-radius: 10rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: $text-secondary;
		font-size: 40rpx;
		transition: all 0.25s;
		background-color: #f9fafb;

		&:hover {
			border-color: $primary-color;
			color: $primary-color;
			background-color: $primary-light;
		}

		.upload-text {
			font-size: 24rpx;
			margin-top: 10rpx;
		}
	}

	.server_Info {
		width: 80%;
		border-radius: 20rpx;
		background: rgba(255, 255, 255, 1);
		box-shadow: 0rpx 2rpx 4rpx rgba(0, 0, 0, 0.25);
		margin: 0 auto;
		margin-top: 38rpx;
		padding: 45rpx 60rpx 60rpx;
		margin-bottom: 60rpx;
	}

	.info-section {
		margin-bottom: 40rpx;
	}

	.info-label {
		color: $text-primary;
		font-size: 28rpx;
		margin-bottom: 15rpx;
		font-weight: 500;
	}

	.avatar-upload {
		display: flex;
		flex-direction: column;
	}

	.avatar-preview {
		width: 160rpx;
		height: 160rpx;
		border-radius: 10rpx;
		overflow: hidden;
		position: relative;
		margin-bottom: 10rpx;

		image {
			width: 100%;
			height: 100%;
			display: block;
		}
	}

	.banner-upload {
		display: flex;
		flex-direction: column;
	}

	.upload-banner-btn {
		width: 100%;
		height: 78rpx;
		border: 2px dashed $border-color;
		border-radius: 10rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: $text-secondary;
		font-size: 40rpx;
		transition: all 0.25s;
		background-color: #f9fafb;

		&:hover {
			border-color: $primary-color;
			color: $primary-color;
			background-color: $primary-light;
		}

		.upload-text {
			font-size: 24rpx;
			margin-left: 10rpx;
		}
	}

	.banner-preview-container {
		position: relative;
		width: 100%;
		height: 78rpx;
		margin-bottom: 10rpx;
		overflow: hidden;
	}

	.banner-preview {
		width: 100%;
		height: 100%;
		border-radius: 10rpx;
		overflow: hidden;

		image,
		video {
			width: 100%;
			height: 100%;
			display: block;
			object-fit: cover;
		}

		video {
			object-fit: fill;
		}
	}

	.error-message {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #fef2f2;
		color: $required-color;
		font-size: 24rpx;
	}

	.delete-btn {
		position: absolute;
		top: 5rpx;
		right: 5rpx;
		width: 48rpx;
		height: 48rpx;
		border-radius: 50%;
		background-color: $delete-color;
		color: white;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		z-index: 100;
		cursor: pointer;
		transition: all 0.2s;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);

		&:hover {
			background-color: #c53030;
			transform: scale(1.2);
			box-shadow: 0 3px 6px rgba(0, 0, 0, 0.3);
		}
	}

	.format-hint {
		font-size: 22rpx;
		color: $text-placeholder;
		margin-top: 5rpx;
	}

	.text-input {
		height: 70rpx;
		border: 1px solid $border-color;
		border-radius: 8rpx;
		padding: 0 20rpx;

		input {
			width: 100%;
			height: 100%;
			font-size: 26rpx;
		}
	}

	.textarea-input {
		border: 1px solid $border-color;
		border-radius: 8rpx;
		padding: 20rpx;

		textarea {
			width: 100%;
			font-size: 26rpx;
			line-height: 1.5;
			min-height: 150rpx;
		}
	}

	.submit-btn {
		width: 100%;
		height: 80rpx;
		background-color: $primary-color;
		color: white;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
		font-weight: 500;
		margin-top: 20rpx;
		box-shadow: $shadow-sm;
		transition: background-color 0.2s;

		&:hover {
			background-color: #2a5caa;
		}
	}

	.jiancha {
		display: flex;
		width: 159rpx;
		height: 45rpx;
		border-radius: 5rpx;
		background: rgba(23, 162, 184, 1);
		color: white;
		margin-left: 72rpx;
		margin-top: 48rpx;
		font-size: 24rpx;
		line-height: 42rpx;
		align-items: center;
		justify-content: center;
		cursor: pointer;

		image {
			width: 35rpx;
			height: 35rpx;
			margin-top: 5rpx;
			margin-left: 8rpx;
		}
	}

	.server_ip {
		width: 609rpx;
		margin: 0 auto;
		margin-top: 14rpx;

		.server_input {
			height: 61rpx;
			opacity: 1;
			width: 100%;
			border-radius: 5rpx;
			background: rgba(255, 255, 255, 1);
		}

		.server_name {
			color: white;
			font-size: 24rpx;
			margin-bottom: 8rpx;
		}
	}

	.bg-image {
		background: rgba(50, 56, 62, 1);
		width: 750rpx;
		height: 101rpx;
		border-radius: 5rpx 5rpx 0rpx 0rpx;
		padding-top: 1rpx;
		display: flex;
		font-size: 48rpx;
		font-weight: 400;
		color: white;
		align-items: center;

		.title {
			margin-top: 0;
			margin-left: 19rpx;
		}

		.bg_img {
			margin-top: 0;
			margin-left: 26rpx;

			image {
				width: 45rpx;
				height: 45rpx;
			}
		}
	}

	.bg_box {
		width: 750rpx;
		height: 372rpx;
		opacity: 1;
		background: rgba(52, 58, 64, 1);
		padding-top: 20rpx;
	}

	.REST_box {
		display: flex;
		padding-left: 15rpx;
		padding-right: 15rpx;
		margin-top: 10rpx;

		.REST {
			width: 248rpx;
		}
	}

	.IPserver {
		display: flex;
		width: 609rpx;
		margin: 0 auto;

		.serverinfo_l {
			width: 70%;
		}

		.serverinfo_r {
			margin-left: 20rpx;
			width: 30%;
		}
	}
</style>
